package design.clone;

public class Test {
    public static void main(String[] args) {
        Wife w1 = new Wife();
        w1.setName("XiaoHong");
        Husband h1 = new Husband();
        h1.setWife(w1);
        h1.setAge(50);
        h1.setName("DaMing");
        Husband h2 = null;
        try {
            System.out.println(h1);// design.clone.Husband@15db9742
            h2 = (Husband) h1.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        h1.setAge(51);
        h1.setName("DaShan");
        h1.setWife(h1.getWife().setName("WangWu"));
        System.out.println(h2.age+","+h2.name+","+h2.getWife().getName());
//        Husband h2 = new Husband();
//        h2.setAge(h1.getAge());
//        h2.setName(h1.getName());
//        h2.setWife(h1.getWife());
    }
}
class Husband implements Cloneable {
    @Override
    public Object clone() throws CloneNotSupportedException {
//        Husband husband = new Husband();
//        husband.setAge(this.getAge());
//        husband.setName(this.getName());
//        husband.setWife((Wife)(this.getWife().clone()));
//        return husband;
        Object obj = super.clone();
        System.out.println((Husband)obj); // design.clone.Husband@6d06d69c
        System.out.println((Husband)obj == this); // false
        System.out.println(this.equals((Husband)obj)); // false
        ((Husband)obj).setWife((Wife)(this.getWife().clone()));
        return obj;
    }
    String name;
    int age;
    Wife wife;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Wife getWife() {
        return wife;
    }
    public void setWife(Wife wife) {
        this.wife = wife;
    }
}
class Wife implements Cloneable {
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Wife wife = new Wife();
        wife.setAge(this.getAge());
        wife.setName(this.getName());
        return wife;
    }
    String name;
    int age;
    public String getName() {
        return name;
    }
    public Wife setName(String name) {
        this.name = name;
        return this;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}